<?php

/**
 * 这张表的数据保存到另一个库里面用于统计
 */
class GuestDataModel extends BaseModel {
    public static $db;
    //分表需要设置其表，所以需要这样控制,然后每天的数据都存储在这里面，，，，，去统计，，，，，然后数据统计起来，
    //这个数据放在其它的地方？？？？？而且这数据连接去其它的地方，，，，，
    //不用删除，一年的数据都在这里，，，，，
    public static $strTableName = '{{guest_data}}';

    public function init(){
        $this->getDbConnection();
        //是否有存在这张表，如果不存在则会抛出错误，则创建表。。。。。
        $connection=self::$db;
        $strTableName = str_replace(array('{', '}'), '', Yii::app()->db_count->tablePrefix . self::$strTableName);
        $command=$connection->createCommand("SHOW CREATE TABLE {$strTableName}");
        try {
            $rowCount=$command->execute();
        } catch (Exception $e) {
            $sql = "CREATE TABLE `{$strTableName}` (
    `GuestID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID',
    `Url` VARCHAR(500) NOT NULL COMMENT '访问链接',
    `Module` VARCHAR(25) NOT NULL COMMENT '模块',
    `Controller` VARCHAR(25) NOT NULL COMMENT '控制器',
    `Action` VARCHAR(25) NOT NULL COMMENT '方法',
    `IsAd` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' COMMENT '是否是广告',
    `AdMark` VARCHAR(50) NOT NULL COMMENT '广告标识',
    `UserID` INT(11) UNSIGNED NOT NULL DEFAULT '0' COMMENT '用户ID',
    `MarkID` VARCHAR(50) NOT NULL COMMENT '在用户那留了一年的一个cookie信息',
    `SessionID` VARCHAR(50) NOT NULL COMMENT '在用户那留了一天的一个cookie信息',
    `Referer` VARCHAR(255) NOT NULL COMMENT '上一个来源',
    `RefererDomain` VARCHAR(255) NOT NULL COMMENT '来源的域名',
    `RefererRootDomain` VARCHAR(255) NOT NULL COMMENT '来源的根域名',
    `Ip` VARCHAR(255) NOT NULL COMMENT '用户的IP',
    `Browser` VARCHAR(255) NOT NULL COMMENT '浏览器',
    `Query` VARCHAR(255) NOT NULL COMMENT 'get参数是什么',
    `Year` INT(4) UNSIGNED NOT NULL DEFAULT '0' COMMENT '年',
    `Month` TINYINT(2) UNSIGNED NOT NULL DEFAULT '0' COMMENT '月',
    `Day` TINYINT(2) UNSIGNED NOT NULL DEFAULT '0' COMMENT '日',
    `GoodsID` INT(11) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品ID',
    `CatID` INT(11) UNSIGNED NOT NULL DEFAULT '0' COMMENT '分类ID',
    `ModuleID` INT(11) UNSIGNED NOT NULL DEFAULT '0' COMMENT '模块ID',
    `TagIDs` VARCHAR(500) NOT NULL COMMENT '标签列表',
    `AddTime` INT(11) UNSIGNED NOT NULL DEFAULT '0' COMMENT '添加时间',
    PRIMARY KEY (`GuestID`)
)
COMMENT='用户访问记录表\r\n用户访问的记录'
COLLATE='gbk_chinese_ci'
ENGINE=MyISAM;
";

            $command=$connection->createCommand($sql);
            $rowCount=$command->execute();
        }
        
    }

    public function tableName() {
        $this->init();
        return self::$strTableName;
        //return $strTableName;
    }

    public function rules() {
        return array(
            array('Url, Module, Controller, Action, IsAd, AdMark, UserID, MarkID, SessionID, Referer, RefererDomain, RefererRootDomain, Ip, Browser, Query, Year, Month, Day, GoodsID, CatID, ModuleID, AddTime, TagIDs', 'safe'),
        );
    }



    public function getDbConnection(){
        if(self::$db!==null){
            return self::$db;
        }else{
            self::$db=Yii::app()->getComponent('db_count');
            if(self::$db instanceof CDbConnection)
                return self::$db;
            else
                throw new CDbException('连接出错');                    
        }            
    }

    //数据保存前操作
    protected function beforeSave() {
        if ($this->isNewRecord) {

            //记录广告
            $this->AdMark = self::isAd($this->Url);
            $key = 'guest_' . $this->MarkID;
            if (!empty($this->AdMark)) {
                $this->IsAd = 1;
                Yii::app()->cache->set($key, $this->AdMark, 300);
            } else {
                $AdMark = Yii::app()->cache->get($key);
                if ($AdMark) {
                    $this->IsAd = 1;
                    $this->AdMark = $AdMark;
                    //更新
                    Yii::app()->cache->set($key, $AdMark, 300);
                }
            }

            //记录来源域名
            $arrDomain = self::getDomain($this->Referer);
            $this->RefererRootDomain = $arrDomain['RootDomain'];
            $this->RefererDomain = $arrDomain['Domain'];
        }
        return true;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 返回当前用户标识
     * @return string 标识
     */
    public function getMarkId() {
        $cookie = Yii::app()->request->getCookies();
        if (empty($cookie['_guest'])) {
            $id = md5(GuestInfo::getAgent() . $this->getForwardedForIp());
            $cookie = new CHttpCookie('_guest', $id);
            $cookie->expire = time() + 60 * 60 * 24 * 30 * 12; //有限期
            Yii::app()->request->cookies['_guest'] = $cookie;
            return $id;
        } else {
            return $cookie['_guest']->value;
        }
    }

    /**
     * 返回用于当前用户，今天的用户标识
     * @return type
     */
    public function getDayMarkId() {
        $cookie = Yii::app()->request->getCookies();
        if (empty($cookie['_guestday'])) {
            $id = md5(GuestInfo::getAgent() . $this->getForwardedForIp());
            $cookie = new CHttpCookie('_guestday', $id);
            $jin = strtotime(date("Y-m-d 23:59:59")) - time();
            if ($jin < 0) {
                $jin = 0;
            }
            $cookie->expire = time() + (int) $jin; //有限期
            Yii::app()->request->cookies['_guestday'] = $cookie;
            return $id;
        } else {
            return $cookie['_guestday']->value;
        }
    }

    /**
     * 获取阿里云通过SLB负载均衡取得客户端IP
     * @return String ip地址
     */
    public function getForwardedForIp() {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = trim($ip[0]);
            return $ip ? $ip : '127.0.0.1';
        }
        return Yii::app()->request->userHostAddress;
    }

    /**
     * 是否通过广告来的链接
     * @param type $url 当前访问地址
     * @return boolean
     */
    public static function isAd($url) {
        if (empty($url)) {
            return '';
        }
        $parse = @parse_url($url);
        if (empty($parse) || empty($parse['query'])) {
            return '';
        }
        $arrDatas = AdModel::getListName();

        parse_str($parse['query'], $query);
        //print_r($query);exit;
        if (isset($query['qz_gdt'])) {
            return 'tengxun';
        }        
        if (isset($query['tj']) && isset($arrDatas[$query['tj']])) {
            return $query['tj'];
        }
        return '';
    }

    /**
     * 获取一级域名，例如：www.1zw.com 取得 1zw.com部分
     * @param type $url
     * @return array array('root_domain','domain')
     */
    public static function getDomain($url) {
        $host = strtolower($url);
        if (strpos($host, '/') !== false) {
            $parse = @parse_url($host);
            $host = $parse ['host'];
        }
        $topleveldomaindb = array('com', 'edu', 'gov', 'int', 'mil', 'net', 'org', 'biz', 'info', 'pro', 'name', 'museum', 'coop', 'aero', 'xxx', 'idv', 'mobi', 'cc', 'me', 'com.cn');
        $str = '';
        foreach ($topleveldomaindb as $v) {
            $str .= ($str ? '|' : '') . $v;
        }
        $matchstr = "[^\.]+\.(?:(" . $str . ")|\w{2}|((" . $str . ")\.\w{2}))$";
        if (preg_match("/" . $matchstr . "/ies", $host, $matchs)) {
            $domain = $matchs ['0'];
        } else {
            $domain = $host;
        }
        return array('RootDomain' => $domain, 'Domain' => $host);
    }


    //记录
    public function record() {
        if (in_array(ACTION_NAME, array('error')) || IS_AJAX || IS_POST) {
            return true;
        }
        $arrData = array(
            'Url' => Yii::app()->request->hostInfo . Yii::app()->request->getUrl(),
            'Module' => GROUP_NAME,
            'Controller' => CONTROLLER_NAME,
            'Action' => ACTION_NAME,
            'UserID' => yii::app()->user->id,
            'MarkID' => $this->getMarkId(),
            'SessionID' => $this->getDayMarkId(),
            'Referer' => GuestInfo::getReferer(),
            'Ip' => $this->getForwardedForIp(),
            'Browser' => GuestInfo::getBrowser(),
            'Query' => GuestInfo::getQuery(),
            'GoodsID' => yii::app()->request->getParam('gid'),
            'CatID' => yii::app()->request->getParam('cid'),
            'ModuleID' => yii::app()->request->getParam('mid'),
            'TagIDs' => yii::app()->request->getParam('tid'),
            'AddTime' => TIME_TIME,            //记录时间
            'Year'=> date('Y', TIME_TIME),
            'Month'=> date('m', TIME_TIME),
            'Day'=> date('d', TIME_TIME),
        );
        //记录访客日志，调试模式下不记录
        if ((defined('YII_CESHI')) || defined('YII_DEBUG') && YII_DEBUG == false) {
            try {
                @RedisCluster::getInstance()->push('guest_record', $arrData);
            } catch (Exception $exc) {
                
            }
        }
    }

}
